package com.yuanlrc.base.service.admin;

import com.yuanlrc.base.bean.PageBean;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import com.yuanlrc.base.dao.admin.StudentDao;
import com.yuanlrc.base.entity.admin.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentService {
    
    @Autowired
    private StudentDao studentDao;

    /**
     * 根据学生主键查询
     * @param id
     * @return
     */
    public Student find(Long id){
        return studentDao.find(id);
    }

    /**
     * 根据学号查询学生
     * @param studentId
     * @return
     */
    public Student findByStudentId(String studentId){
            return studentDao.findByStudentId(studentId);
    }

    /**
     * 保存学生信息
     * @param student
     * @return
     */
    public Student save(Student student){
        return studentDao.save(student);
    }

    /**
     * 查询所有学生信息
     * @return
     */
    public List<Student> findAll(){
        return studentDao.findAll();
    }

    /**
     * 学号是否存在
     * @param studentId
     * @param id
     * @return
     */
    public boolean isExistStudentId(String studentId,Long id){
        Student student = studentDao.findByStudentId(studentId);
        if(student != null){
            //表示学号存在，接下来判断是否是编辑用户的本身
            if(student.getId().longValue() != id.longValue()){
                return true;
            }
        }
        return false;
    }

    /**
     * 分页查询学生列表
     * @param student
     * @param pageBean
     * @return
     */
    public PageBean<Student> findList(Student student, PageBean<Student> pageBean){
        ExampleMatcher withMatcher = ExampleMatcher.matching().withMatcher("studentName", ExampleMatcher.GenericPropertyMatchers.contains());
        withMatcher = withMatcher.withIgnorePaths("sex");
        Example<Student> example = Example.of(student, withMatcher);
        Pageable pageable = PageRequest.of(pageBean.getCurrentPage()-1, pageBean.getPageSize());
        Page<Student> findAll = studentDao.findAll(example, pageable);
        pageBean.setContent(findAll.getContent());
        pageBean.setTotal(findAll.getTotalElements());
        pageBean.setTotalPage(findAll.getTotalPages());
        return pageBean;
    }

    /**
     * 删除学生
     * @param id
     */
    public void delete(Long id){
        studentDao.deleteById(id);
    }

    /**
     * 返回学生总数
     * @return
     */
    public long total(){
        return studentDao.count();
    }

}
